﻿// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	SmartLib
//  File name:	CtxElevator.cs
//  Developer:	Igor Solomatov
//  Created:	12.11.2012
// 
// -------------------- iSharePoint -------------------- //

using System;

namespace Smart
{
	public class CtxElevator<TContextType> : IDisposable
		where TContextType : CtxInfo
	{
		protected CtxStack<TContextType> CtxStack;
		protected TContextType Ctx;

		public CtxElevator(CtxStack<TContextType> ctxStack, TContextType ctx)
		{
			ctxStack.PushCtx(ctx);

			CtxStack = ctxStack;
			Ctx = ctx;
		}

		#region IDisposable Members

		/// <summary>
		/// Flag whether class were disposed
		/// </summary>
		protected volatile bool Disposed;

		/// <summary>
		/// Dispose underlying resources
		/// </summary>
		public void Dispose()
		{
			Dispose(true);

			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// Dispose underlying resources
		/// </summary>
		/// <param name="disposing">flag whether method called by user directly</param>
		protected virtual void Dispose(bool disposing)
		{
			if (Disposed)
				return;

			if (disposing)
			{
				DisposeManaged();
			}

			DisposeUnmanaged();

			Disposed = true;
		}

		/// <summary>
		/// Dispose managed resources. Method called only once.
		/// </summary>
		protected virtual void DisposeManaged()
		{
			if (CtxStack != null && Ctx != null)
				CtxStack.FreeCtx(Ctx.CtxIndex);

			CtxStack = null;
			Ctx = null;
		}

		/// <summary>
		/// Dispose unmanaged resources. Method called only once.
		/// </summary>
		protected virtual void DisposeUnmanaged()
		{
		}

		~CtxElevator()
		{
			Dispose(false);
		}

		#endregion
	}
}